// Copyright 2007 Google Inc.
// All Rights Reserved.

package com.google.jessewilson.codesearch.gtagssearch;

import com.google.jessewilson.codesearch.api.CodeFile;
import com.google.jessewilson.codesearch.api.Line;
import com.google.jessewilson.codesearch.io.Path;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Parses lines of output from the Gtags executable into Line objects.
 *
 * @author Ted Mao (tmao@google.com)
 */
public class GtagsResultParser {

  private static final Pattern PATTERN =
      Pattern.compile("\\* (.+?):(\\d+)\\s*(.*)");

  private final GtagsSearchProviderBackend provider;

  public GtagsResultParser(GtagsSearchProviderBackend provider) {
    this.provider = provider;
  }

  /**
   * Parses a single result line from gtags and returns a Line object
   *
   * @param resultLine result line from gtags
   * @return result line parsed into a Line object
   */
  public Line parse(String resultLine) {
    Matcher m = PATTERN.matcher(resultLine);
    if (!m.matches()) {
      throw new IllegalArgumentException(
          "Input is not parseable: " + resultLine);
    }
    CodeFile codeFile = new CodeFile();
    String path = m.group(1);
    codeFile.setPath(Path.fromString(path));
    codeFile.setId(path);
    codeFile.setSearchProvider(provider);

    Line line = new Line();
    line.setCodeFile(codeFile);
    // TODO FIXME: not sure why we need -1, but otherwise the line displayed in
    // search results is off by one
    line.setLineNumber(Integer.parseInt(m.group(2))-1);
    line.setLineValue(m.group(3));
    return line;
  }
}
